from tastypie.resources import ModelResource
from tastypie import  fields
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from m.models import Video, Shot, Status
from tastypie.authorization import Authorization
from worker import client
import traceback

class VideoResource(ModelResource):
    def obj_create(self, bundle, request=None, **kwargs):
        b = super(VideoResource, self).obj_create(bundle, request, **kwargs)
        #v = Video
        v = b.obj
        try:
            client.transcode(videoid=v.id)
        except:
            #v = Video
            v.error = traceback.format_exc()
            v.status_transcode = Status.FAIL
            v.save()
        return b

    class Meta:
        include_resource_uri = False
        queryset = Video.objects.all()
        include_resource_uri = False
        resource_name = 'video'
        filtering = {
            'id': ['exact'],
            #'pub_date': ['exact', 'lt', 'lte', 'gte', 'gt'],
        }
        authorization = Authorization()



class ShotResource(ModelResource):
    video = fields.ForeignKey(VideoResource,'video')
    class Meta:
        #include_resource_uri = False
        #include_absolute_url = True
        queryset = Shot.objects.all()
        resource_name = 'shot'
        filtering = {
            'video': ALL_WITH_RELATIONS,
            #'pub_date': ['exact', 'lt', 'lte', 'gte', 'gt'],
        }

#http://127.0.0.1:8000/api/v1/shot/?video__id=3&limit=0